<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            top: 100px;
            width: 100px;
            height: 100px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <button class="button_300">点击前进300距离</button>
    <button class="button_600">点击前进600距离</button>
    <div>动画盒子</div>

    <script>
        //1.获取案例和盒子
        var button300 = document.querySelector('.button_300');
        var button600 = document.querySelector('.button_600');
        var div = document.querySelector('div');
        
        button300.addEventListener('click', function () {
            animation(div, 300, function(){
                div.style.backgroundColor = 'red';
            });
        })

        button600.addEventListener('click', function() {
            animation(div, 600, function () {
                div.style.backgroundColor = 'green';
            });
        })

        
        // 定义缓动动画的函数
        function animation(obj, target, callback) {
            clearInterval(obj.timer);
            obj.timer = setInterval(() => {
                if (obj.offsetLeft == target) {
                clearInterval(obj.timer);
                if (callback) {
                    callback();
                } 
            }
            //核心算法：`（目标值-现在的位置）/ 10`作为每次移动的距离步长
            // 这里的算法其实有一个问题， 就是移动后的距离其实并不是整数，
            // 因为直接这样算出来的肯定是会有小数点的
            var step = (target - obj.offsetLeft)/10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            obj.style.left = obj.offsetLeft + step + 'px';
            }, 30);
        }
    </script>
</body>
</html>